package com.crm.controller.saling;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.crm.pojo.*;
import com.crm.service.before_sale.SalePlanService;
import com.crm.service.client.ClientInfoService;
import com.crm.service.permission.UserInfoService;
import com.crm.service.productionService.ProductionDetilsService;
import com.crm.service.saling.CODetailsService;
import com.crm.service.saling.ContractService;
import com.crm.vo.CODetailsVO;
import com.crm.vo.ContractVO;
import com.crm.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;

/**
 * Created by dr5hx on 2018/8/3
 */
@RequestMapping("saling")
@Controller
public class ContractController {
    @Autowired
    private ContractService contractService;
    @Autowired
    private ClientInfoService clientInfoService;
    @Autowired
    private CODetailsService coDetailsService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private SalePlanService salePlanService;
    @Autowired
    private ProductionDetilsService productionDetilsService;

    /**
     * 跳转到合同列表页面
     *
     * @return
     */
    @GetMapping("contractList")
    public String toContractList() {
        return "saling/ContractList";
    }

    /**
     * 分页显示的合同json数据
     *
     * @param page
     * @param rows
     * @return
     */
    @GetMapping("getContractList")
    @ResponseBody
    public Map getContractInformation(int page, int rows) {
        try {
            List<ContractVO> list = contractService.showContractAllList(page, rows);
            Long count = contractService.getContractExistCount();
            Map map = new HashMap();
            map.put("rows", list);
            map.put("total", count);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 删除合同
     *
     * @param contractId
     * @return
     */
    @PostMapping("deleteContractById")
    @ResponseBody
    public Result deleteContractById(String contractId) {
        try {
            Long id = contractId == null ? 0 : new Long(contractId);
            return contractService.deleteContractById(id);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return new Result("something unexpected happened ");
        }
    }

    /**
     * 加载合同数据
     *
     * @param id
     * @return
     */
    @PostMapping("loadOneContractVO")
    @ResponseBody
    public ContractVO showLoadContract(String id) {
        try {
            Long contractId = id == null ? 0L : new Long(id);
            ContractVO contractVO = contractService.getLoadContractVO(contractId);

            return contractVO;
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 显示合同对应的详单列表
     *
     * @param contractId
     * @return
     */
    @PostMapping("loadCODetailsList")
    @ResponseBody
    public List<CODetailsVO> showCODetailsList(Long contractId) {
        try {
            Long cid = contractId == null ? 0L : contractId;
            return coDetailsService.showOrderDetailsList(cid);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 转发到编辑合同列表
     *
     * @return
     */
    @PostMapping("toLoadContract")
    public String toLoadContractList() {
        return "saling/loadContract";
    }

    /**
     * 转发的添加合同页面
     *
     * @return
     */
    @PostMapping("toAddContract")
    public String toAddContractList() {
        return "saling/addContract";
    }

    /**
     * test
     * 获取合同列表
     *
     * @return
     */

    @GetMapping("showList")
    @ResponseBody
    public List<ContractVO> toShowContractList() {
        return contractService.showContractList();
    }

    @GetMapping("dr5hxTest")

    public String dr5hxTest() {

        return "saling/ContractList";
    }

    /**
     * 加载联系人信息
     *
     * @param cid
     * @return
     */
    @PostMapping("loadContactInformation")
    @ResponseBody
    public List<Contact> toLoadContactInformation(Long cid) {
        try {
            cid = cid == null ? 0L : cid;
            return clientInfoService.queryContactByCid(cid);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取所有员工信息
     *
     * @return
     */
    @PostMapping("getUserInfoList")
    @ResponseBody
    public List<Userinfo> getUserInfoList() {
        try {
            return userInfoService.getUserInfoList();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取客户列表
     *
     * @return
     */
    @PostMapping("getClientInfoList")
    @ResponseBody
    public List<ClientInfo> getClientInfo() {

        try {
            return clientInfoService.getClientInfoList();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取对应客户销售计划
     *
     * @param cid
     * @return
     */
    @PostMapping("getCustomerPlan")
    @ResponseBody
    public List<SalePlan> getSalePlan(Long cid) {
        try {
            cid = cid == null ? 0L : cid;
            return salePlanService.showCustomerPlan(cid);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 添加合同信息
     *
     * @param contract
     * @return
     */
    @PostMapping("uploadContractInformation")
    @ResponseBody
    public Result saveContract(Contract contract, @RequestParam("contractAccessoryname") CommonsMultipartFile file,
                               HttpServletRequest request) throws IOException {
        try {
            contract = contract == null ? new Contract() : contract;
            getFile(file, request, contract);
            contract.setContractIsDel("否");
            contract.setOrderStartTime(new Date());
            contract.setContractCheck("未审核");
            contract.setContractIsRefund("无");
            contract.setOrderBackMoney(new BigDecimal(0));
            contract.setContractDoTime(new Date());
            contractService.saveContract(contract);
            return Result.SUCCESS;
        } catch (IOException e) {
            e.printStackTrace();
            return new Result("some unexpeted happned");
        }
    }

    private String ext(String fileName) {
        int pos = fileName.lastIndexOf('.');
        if (pos == -1) {
            return "";
        }
        return fileName.substring(pos);//带.
    }

    /**
     * 转发到添加合同详情页面
     *
     * @return
     */

    @PostMapping("toContractDetailsForm")
    public String toContractDetailsForm() {
        return "saling/addCODetailsForm";
    }

    /**
     * 模糊获取产品列表
     *
     * @param productName
     * @return
     */
    @PostMapping("fuzzyQueryProductDetailsList")
    @ResponseBody
    public List<ProductionDetail> fuzzyQueryProductDetailsList(@RequestParam("q") String productName) {
        try {
            productName = productName == null ? "" : productName;
            return productionDetilsService.fuzzyQueryByProductName(productName);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 精准获取产品详细信息
     *
     * @param id
     * @return
     */
    @PostMapping("exactQueryProductDetail")
    @ResponseBody
    public ProductionDetail exactQueryProductDetail(Long id) {
        try {
            id = id == null ? 0L : id;
            return productionDetilsService.exactQueryProductDetail(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 新建一个合同详情
     *
     * @param id
     * @param coDetail
     * @return
     */
    @PostMapping("addCODetail")
    @ResponseBody
    public Result addCODetailByContract(Long id, CODetail coDetail) {
        try {
            if (coDetail != null && id != null) {
                coDetail.setCOCompleteAccount(new BigDecimal(0));
                coDetail.setCODetailsIsDel("否");
                coDetail.setCOState("未完成");
                coDetail.setFkOrderId(new BigDecimal(0));
                coDetail.setProductType("0");
                coDetailsService.saveCODetail(coDetail, id);
                return Result.SUCCESS;
            } else {
                return new Result("failed add contract details");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("unexpeted happend");
        }
    }

    /**
     * 转发到详情编辑页面
     *
     * @return
     */
    @PostMapping("editCODetail")
    public String toEditCODetails() {
        return "saling/editCODetails";
    }

    /**
     * 远程加载一个合同详情数据
     *
     * @param coId
     * @return
     */
    @PostMapping("getOneCODetail")
    @ResponseBody
    public CODetailsVO getOneCODetail(Long coId) {
        try {
            coId = coId == null ? 0 : coId;
            return coDetailsService.getOneCODetail(coId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /***
     *提交修改的详细得合同细节
     * @param coDetail
     * @return
     */
    @PostMapping("doEditCODetail")
    @ResponseBody
    public Result editCODetail(CODetail coDetail) {
        try {
            if (coDetail != null) {
                CODetail c = coDetailsService.getOneCODetail(coDetail.getCOId()).getCoDetail();
                c.setCOPrice(coDetail.getCOPrice());
                c.setCOAmount(coDetail.getCOAmount());
                c.setCOMoney(coDetail.getCOMoney());
                c.setCOTime(coDetail.getCOTime());
                c.setCORemark(coDetail.getCORemark());
                coDetailsService.saveEditCODetail(c);
                return Result.SUCCESS;
            } else {
                return new Result();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("some unexpeted happened");
        }
    }

    /**
     * 修改合同
     *
     * @param contract
     * @param contactId
     * @param empno
     * @param fkplanid
     * @return
     */
    @PostMapping("saveEditContract")
    @ResponseBody
    public Result saveEditContract(Contract contract, @RequestParam("fkCustomerId1") String contactId, @RequestParam("contractEmpno1") String empno,
                                   @RequestParam("fkPlanId1") String fkplanid, @RequestParam("uploadfile") CommonsMultipartFile file,
                                   HttpServletRequest request) throws IOException {
        if (contract.getContractId() != null) {
            Contract c = contractService.getLoadContractVO(contract.getContractId()).getContract();
            if (contract.getContractTopic() != null) {
                c.setContractTopic(contract.getContractTopic());
            }
            if (contract.getContractMoney() != null) {
                c.setContractMoney(contract.getContractMoney());
            }
            if (contract.getOrderStartTime() != null) {
                c.setOrderStartTime(contract.getOrderStartTime());
            }
            if (contract.getOrderOverTime() != null) {
                c.setOrderOverTime(contract.getOrderOverTime());
            }
            if (contract.getContractState() != null) {
                c.setContractState(contract.getContractState());
            }
            if (contract.getContractRemark() != null) {
                c.setContractRemark(contract.getContractRemark());
            }
            if (contract.getContractAddress() != null) {
                c.setContractAddress(contract.getContractAddress());
            }
            if (contactId != null && isInteger(contactId)) {
                c.setFkCustomerId(new BigDecimal(Integer.parseInt(contactId)));
            }
            if (empno != null && isInteger(empno)) {
                c.setContractEmpno(new BigDecimal(Integer.parseInt(empno)));

            }
            if (fkplanid != null && isInteger(fkplanid)) {
                c.setFkPlanId(new BigDecimal(Integer.parseInt(fkplanid)));
            }
            getFile(file, request, c);
            c.setContractDoTime(new Date());
            contractService.saveContract(c);
            return Result.SUCCESS;
        } else {
            return new Result("修改失败");
        }
    }

    private boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^-?[1-9]\\d*$");
        return pattern.matcher(str).matches();
    }

    private void getFile(CommonsMultipartFile file, HttpServletRequest request, Contract c) throws IOException {
        if (file.getSize() != 0) {
            ServletContext application = request.getServletContext();
            String dir = application.getRealPath("\\uploadsAccessory");
            File uploads = new File(dir);
            if (!uploads.exists()) uploads.mkdirs();
            //将文件名改成唯一的新名称
            String newFileName = UUID.randomUUID().toString().toUpperCase()
                    + ext(file.getOriginalFilename());
            File fullFileName = new File(uploads, newFileName);
            //保存文件
            file.transferTo(fullFileName);
            c.setContractAccessory(dir + newFileName);
        }
    }

    @PostMapping("deleteCOdetail")
    @ResponseBody
    public Result deleteCOdetail(Long contractId, String rows) {
        try {
            if (contractId != null && rows != null) {
                System.out.println(rows);
                List<CODetailsVO> list = coDetailsService.showOrderDetailsList(contractId);
                List<CODetail> coDetailList = new ArrayList<>();
                JSONObject jsonObject = JSON.parseObject(rows);
                System.out.println(jsonObject);
                BigDecimal a = new BigDecimal(jsonObject.getJSONObject("coDetail").get("cOId").toString());
                for (CODetailsVO coDetailsVO : list) {
                    if (new BigDecimal(coDetailsVO.getCoDetail().getCOId().toString()).equals(a)) {
                        coDetailsVO.getCoDetail().setCODetailsIsDel("是");
                        coDetailList.add(coDetailsVO.getCoDetail());
                    }
                }
                coDetailsService.saveCoDetailList(coDetailList);
                return Result.SUCCESS;
            } else {
                return new Result("参数解析错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("some unexpected happened");
        }

    }
}
